<template>
  <div class="container">
    <Breadcrumb :items="['系统管理', '菜单管理']" />
    <a-card class="general-card" :title="$t('菜单管理')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="name" :label="$t('菜单名称')">
                  <a-input
                    v-model="searchForm.name"
                    :placeholder="$t('请输入菜单名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="1">{{ $t('启用') }}</a-option>
                    <a-option :value="0">{{ $t('禁用') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-button type="primary" @click="openAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            {{ $t('新增') }}
          </a-button>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="false"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="菜单名称" data-index="name" />
          <a-table-column title="图标" data-index="icon">
            <template #cell="{ record }">
              <component :is="record.icon || 'icon-apps'" />
            </template>
          </a-table-column>
          <a-table-column title="路径" data-index="path" />
          <a-table-column title="组件路径" data-index="component" />
          <a-table-column title="排序" data-index="orderNum" />
          <a-table-column title="权限标识" data-index="perms" />
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime" />
          <a-table-column title="操作" fixed="right" :width="150">
            <template #cell="{ record }">
              <a-button
                type="text"
                size="small"
                @click="openEditDialog(record)"
              >
                编辑
              </a-button>
              <a-button
                type="text"
                status="danger"
                size="small"
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑菜单' : '新增菜单'"
      @before-ok="handleSubmit"
      @close="() => { console.log('对话框关闭'); }"
      @cancel="() => { console.log('对话框取消'); }"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="right"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="parentId" label="上级菜单">
          <a-tree-select
            v-model="form.parentId"
            :data="treeData"
            placeholder="请选择上级菜单"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="name" label="菜单名称" required>
          <a-input v-model="form.name" placeholder="请输入菜单名称" />
        </a-form-item>
        <a-form-item field="path" label="菜单路径" required>
          <a-input v-model="form.path" placeholder="请输入菜单路径" />
        </a-form-item>
        <a-form-item field="component" label="组件路径">
          <a-input v-model="form.component" placeholder="请输入组件路径，如：system/menu/index" />
        </a-form-item>
        <a-form-item field="icon" label="菜单图标">
          <a-input v-model="form.icon" placeholder="请输入图标名称" />
        </a-form-item>
        <a-form-item field="orderNum" label="排序">
          <a-input-number
            v-model="form.orderNum"
            placeholder="请输入排序"
            :min="0"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item field="perms" label="权限标识">
          <a-input v-model="form.perms" placeholder="请输入权限标识" />
        </a-form-item>
        <a-form-item field="isHidden" label="是否隐藏">
          <a-radio-group v-model="form.isHidden">
            <a-radio :value="0">显示</a-radio>
            <a-radio :value="1">隐藏</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="isCache" label="是否缓存">
          <a-radio-group v-model="form.isCache">
            <a-radio :value="0">不缓存</a-radio>
            <a-radio :value="1">缓存</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-radio-group v-model="form.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="form.remark" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    getMenuList,
    addMenu,
    updateMenu,
    deleteMenu,
    MenuItem,
  } from '@/api/menu';
  import useLoading from '@/hooks/loading';
  import { cloneDeep } from 'lodash';

  const { loading, setLoading } = useLoading();
  const visible = ref(false);
  const isEdit = ref(false);
  const formRef = ref();
  const menuList = ref<MenuItem[]>([]);
  
  const searchForm = reactive({
    name: '',
    status: undefined,
  });
  
  const form = reactive({
    id: '',
    name: '',
    path: '',
    component: '',
    icon: '',
    parentId: 0,
    orderNum: 0,
    perms: '',
    isHidden: 0,
    isCache: 0,
    status: 1,
    remark: '',
  });
  
  const rules = {
    name: [{ required: true, message: '请输入菜单名称' }],
    path: [{ required: true, message: '请输入菜单路径' }],
  };

  function formatTreeData(data: MenuItem[]) {
    return data.map((item) => ({
      key: item.id,
      title: item.name,
      children: item.children ? formatTreeData(item.children) : undefined,
    }));
  }

  const renderData = computed(() => {
    let result = cloneDeep(menuList.value);
    
    if (searchForm.name) {
      result = result.filter((item) => 
        item.name.toLowerCase().includes(searchForm.name.toLowerCase())
      );
    }
    
    if (searchForm.status !== undefined) {
      result = result.filter((item) => item.status === searchForm.status);
    }
    
    return result;
  });
  
  const treeData = computed(() => {
    const data = cloneDeep(menuList.value);
    return [
      {
        key: 0,
        title: '根菜单',
        children: formatTreeData(data),
      },
    ];
  });

  async function fetchData() {
    setLoading(true);
    try {
      const res = await getMenuList();
      console.log('获取菜单列表响应:', res);
      
      // 检查响应结构
      if (!res) {
        console.error('响应数据为空或格式不正确:', res);
        Message.error('获取菜单列表失败: 响应数据格式不正确');
        setLoading(false);
        return;
      }
      
      // 直接使用响应中的数据
      // 根据控制台输出，res已经是{code: 200, message: '操作成功', data: Array(7)}格式
      if (res.code === 200 && Array.isArray(res.data)) {
        console.log('原始菜单数据:', res.data);
        
        try {
          // 将扁平的菜单数据转换为树形结构
          const buildMenuTree = (items: MenuItem[], parentId: number | string | null = 0) => {
            return items
              .filter(item => {
                // 检查parentId是否匹配
                const itemParentId = typeof item.parentId === 'string' 
                  ? parseInt(item.parentId, 10) 
                  : item.parentId;
                return itemParentId === parentId;
              })
              .map(item => {
                // 确保状态字段是数字类型
                if (typeof item.status === 'string') {
                  item.status = parseInt(item.status, 10);
                }
                
                // 递归查找子菜单
                const children = buildMenuTree(items, item.id);
                if (children.length) {
                  return { ...item, children };
                }
                return item;
              });
          };
          
          menuList.value = buildMenuTree(res.data);
          console.log('处理后的菜单数据:', menuList.value);
        } catch (treeError) {
          console.error('构建菜单树结构时出错:', treeError);
          // 如果构建树结构失败，直接使用原始数据
          menuList.value = res.data.map(item => {
            if (typeof item.status === 'string') {
              item.status = parseInt(item.status, 10);
            }
            return item;
          });
          console.log('使用原始菜单数据:', menuList.value);
        }
      } else {
        console.error('获取菜单列表失败:', res);
        Message.error(`获取菜单列表失败: ${res.message || '未知错误'}`);
      }
    } catch (err) {
      console.error('获取菜单列表异常:', err);
      Message.error('获取菜单列表失败: ' + (err instanceof Error ? err.message : '未知错误'));
    } finally {
      setLoading(false);
    }
  }

  function search() {
    fetchData();
  }

  function reset() {
    searchForm.name = '';
    searchForm.status = undefined;
    fetchData();
  }

  function openAddDialog() {
    isEdit.value = false;
    Object.assign(form, {
      id: '',
      name: '',
      path: '',
      component: '',
      icon: '',
      parentId: 0,
      orderNum: 0,
      perms: '',
      isHidden: 0,
      isCache: 0,
      status: 1,
      remark: '',
    });
    visible.value = true;
  }

  function openEditDialog(record: MenuItem) {
    console.log('打开编辑对话框，记录:', record);
    isEdit.value = true;
    console.log('设置isEdit为:', isEdit.value);
    Object.assign(form, {
      id: record.id,
      name: record.name,
      path: record.path,
      component: record.component || '',
      icon: record.icon || '',
      parentId: record.parentId === null ? 0 : record.parentId,
      orderNum: record.orderNum || 0,
      perms: record.perms || '',
      isHidden: record.isHidden || 0,
      isCache: record.isCache || 0,
      status: record.status,
      remark: record.remark || '',
    });
    console.log('编辑表单数据:', form);
    visible.value = true;
  }

  async function handleSubmit() {
    console.log('提交表单，当前编辑状态:', isEdit.value);
    
    try {
      // 检查formRef是否存在
      if (!formRef.value) {
        console.error('表单引用不存在');
        return false;
      }
      
      // 修改验证方式，使用try-catch捕获可能的错误
      try {
        await formRef.value.validate();
        console.log('表单验证通过');
      } catch (validationError) {
        console.error('表单验证失败:', validationError);
        return false;
      }
      
      // 构建提交数据，确保数据类型与后端一致
      const submitData = {
        ...form,
        parentId: form.parentId === 0 ? null : form.parentId,
        // 确保状态是字符串类型
        status: form.status.toString(),
      };
      
      console.log('提交菜单数据:', submitData);
      console.log('isEdit状态:', isEdit.value);
      
      let res;
      if (isEdit.value) {
        console.log('调用updateMenu接口');
        res = await updateMenu(submitData);
      } else {
        console.log('调用addMenu接口');
        res = await addMenu(submitData);
      }
      
      console.log('提交菜单响应:', res);
      
      if (res.code === 200) {
        Message.success(isEdit.value ? '更新成功' : '添加成功');
        fetchData();
        return true;
      } else {
        Message.error(`${isEdit.value ? '更新' : '添加'}失败: ${res.message || '未知错误'}`);
        return false;
      }
    } catch (err) {
      console.error(`${isEdit.value ? '更新' : '添加'}菜单异常:`, err);
      Message.error(isEdit.value ? '更新失败' : '添加失败');
      return false;
    }
  }

  function handleDelete(record: MenuItem) {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除菜单 "${record.name}" 吗？`,
      onOk: async () => {
        try {
          const res = await deleteMenu(record.id);
          console.log('删除菜单响应:', res);
          
          if (res.code === 200) {
            Message.success('删除成功');
            fetchData();
          } else {
            Message.error(`删除失败: ${res.message || '未知错误'}`);
          }
        } catch (err) {
          console.error('删除菜单异常:', err);
          Message.error('删除失败');
        }
      },
    });
  }

  onMounted(() => {
    fetchData();
  });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
  }
</style> 